<template>
	<view class="container">
		<!-- 订单时间 -->
		<view class="time-section">
			<text class="time-text">订单提交时间：{{ submitTime }}</text>
		</view>

		<!-- 课程信息 -->
		<view class="course-card">
			<view class="course-header">
				<text class="course-title">{{ courseInfo.info.c_name }}</text>
			</view>
			<view class="brief">上课周期 {{ courseInfo.info.week }} | 适合人群： {{ courseInfo.info.person }}</view>
		  
			<view class="teacher-infos">
				<view class="teach-desc">
					<view class="teacher-info" v-for="item in courseInfo.teacher">
						<image class="teacher-avatar" :src="item.thumb"></image>
						<view class="name">{{ item.name }}</view>
					</view>
				</view>
				<view class="price-info">
					<text class="course-price">￥{{ courseInfo.info.price }}</text>
					<text class="count">已报名 {{ courseInfo.info.people }} 人</text>
				</view>
			</view>
		</view>

		<!-- 支付方式 -->
		<view class="payment-section">
			<text class="section-title">选择支付方式</text>
			<view class="payment-item">
				<view class="pay-type" :class="payType == 1 ? 'checked' : ''" @click="checkPay(1)" v-if="weixin">
					<image src="/static/alipay.png" class="payment-icon" />
					<text class="payment-name">支付宝支付</text>
				</view>
				<view class="pay-type" :class="payType == 2 ? 'checked' : ''" @click="checkPay(2)">
					<image src="/static/weipay.png" class="payment-icon" />
					<text class="payment-name">微信支付</text>
				</view>
			</view>
		</view>

		<!-- 底部支付栏 -->
		<view class="footer">
			<view class="price-box">
				<text class="price-label">应付金额：</text>
				<text class="total-price">￥{{ courseInfo.info.price }}</text>
			</view>
			<button class="pay-btn" @click="handlePayment">确认支付</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			baseURL: getApp().globalData.baseUrl,
			submitTime: '',
			payType: 2,
			courseInfo: { },
			appid: uni.getStorageSync('appid'),
			openid: '',
			weixin: true
		}
	},
	onLoad(){
		this.courseInfo = uni.getStorageSync('class')
		uni.setStorageSync('class','')
		this.submitTime = this.formatTime() 
		console.log(this.courseInfo)
		var that  =  this
		uni.getSystemInfo({
			success: function (res) {
				console.log(res.uniPlatform)
				if( res.uniPlatform == 'mp-weixin' ){
					that.weixin = false
					console.log(that.weixin)
				}
			}
		});

	},
	methods: {
		formatTime(date = new Date()) {
			const year = date.getFullYear()
			const month = (date.getMonth() + 1).toString().padStart(2, '0')
			const day = date.getDate().toString().padStart(2, '0')
			const hours = date.getHours().toString().padStart(2, '0')
			const minutes = date.getMinutes().toString().padStart(2, '0')
			const seconds = date.getSeconds().toString().padStart(2, '0')
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		},
		handlePayment() {
			if( this.payType == 1 ){
				this.alipay()   //支付宝支付
			} else if( this.payType == 2 ){
				if( this.weixin ){
					this.wxPay() 
				} else {
					this.mpweixinPay()
				}
			}
		},
		wxPay() {
			var  param = {
				cid:this.courseInfo.info.id,
				appid:this.appid,
			}
			uni.request({
				url: this.baseURL + '/api/wechatpay/index',
				method: 'POST',
				data: param,
				header: { 'Content-Type': 'application/json' },
				success: (res) => {
					let orderInfo = res.data.data.order_arr
					console.log("orderInfo: ",res.data)
					this.startWxPay(orderInfo)
				},
				fail: (err) => {
					console.error('请求失败:', err);
				}
			});
		},
		startWxPay(orderInfo){
			uni.getProvider({
				service: 'payment',
				success(res) {
					uni.requestPayment({
						provider: 'wxpay', 
						'orderInfo': orderInfo,
						success(res) {
							console.log('支付成功', res);
							uni.showToast({ title: '支付成功' });
						},
						fail(err) {
							console.error('支付失败', err);
							uni.showToast({ title: '支付取消或失败', icon: 'error' });
							// uni.showToast({ title: err.errMsg, icon: 'error' });
						}
					})
				}
			})
		},
		checkPay(type){
			this.payType = type
		},
		//支付宝支付
		alipay(){
			var  param = {
				cid:this.courseInfo.info.id,
				appid:this.appid,
			}
			uni.request({
				url: this.baseURL + '/api/alipay/index',
				method: 'POST',
				data: param,
				header: { 'Content-Type': 'application/json' },
				success: (res) => {
					const responseData = res.data.data
					uni.requestPayment({
						provider: 'alipay',
						orderInfo: responseData,
						success: (res) => {
							console.log('支付成功', res);
						},
						fail: (err) => {
							console.error('支付失败', err);
							uni.showToast({ title: '支付取消或失败', icon: 'error' });
						}
					});
				},
				fail: (err) => {
					console.error('请求失败:', err);
				}
			});
		},
		mpweixinPay(){
			var that  =  this
			uni.login({
				provider: 'weixin',
				success: function (loginRes) {
					uni.request({
						url: that.baseURL + '/api/wechatpay/login',
						method: 'POST',
						data: {code:loginRes.code,appid:that.appid},
						header: { 'Content-Type': 'application/json' },
						success: (res) => {
							that.openid  = res.data.data.openid
							//发起微信支付
							setTimeout(function(){
								that.wxPay()
							},500)
						},
						fail: (err) => {
							console.error('请求失败:', err);
						}
					});
				}
			});
		},
		mpwxPay(){
			var  param = {
				cid:this.courseInfo.info.id,
				appid:this.appid,
				openid:this.openid
			}
			console.log( param )
			uni.request({
				url: this.baseURL + '/api/wechatpay/miniPay',
				method: 'POST',
				data: param,
				header: { 'Content-Type': 'application/json' },
				success: (res) => {
					var payParams = res.data.data
					console.log(payParams)
					//发起微信支付
					uni.requestPayment({
						provider: 'wxpay',       
						appId: payParams.appId,    
						timeStamp: payParams.timeStamp, 
						nonceStr: payParams.nonceStr,
						package: payParams.package,   
						signType: payParams.signType, 
						paySign: payParams.paySign,
						success: (result) => {
							uni.switchTab({url: '/pages/class/class'})
						},
						fail: (err) => {
							// 处理支付失败（包括用户取消）
							if (err.errMsg.includes('cancel')) {
								uni.showToast({ title: '支付已取消', icon: 'none' });
							} else {
								uni.showToast({ title: '支付失败', icon: 'none' });
							}
						}
					});
				},
				fail: (err) => {
					console.error('请求失败:', err);
				}
			});
		}
	}
}
</script>

<style>
	.container {padding: 30rpx;background-color: #f8f8f8;min-height: 100vh;padding-bottom: 140rpx;}
	.time-section {padding: 20rpx;background: #fff;border-radius: 12rpx;margin-bottom: 30rpx;}
	.time-text {font-size: 26rpx;color: #666;}
	.course-card {background: #fff;border-radius: 12rpx;padding: 30rpx;margin-bottom: 30rpx;}
	.course-header {display: flex;margin-bottom: 20rpx;justify-content: start;}
	.course-title {font-size: 34rpx;color: #333;font-weight: bold;padding-bottom: 20rpx;}
	.course-price {font-size: 36rpx;color: #EB6E30;font-weight: bold;}
	.brief {font-size: 26rpx;color: #888;margin-bottom: 10rpx;}
	/* 老师信息 */
	.teacher-infos{display: flex;flex-direction: row;justify-content: space-between;align-items: center;padding-top: 40rpx;}
	.teach-desc{display: flex;flex-direction: row;justify-content: start;flex-wrap: wrap;max-width: calc(400rpx);}
	.teacher-info {display: flex;flex-direction: row;align-items: center;flex: 0 0 calc(49% - 15rpx);max-width: calc(200rpx);padding-top: 20rpx;}
	.teacher-info:first-child{margin-left: 0;}
	.name {font-size: 26rpx;color: #888;padding-left: 10rpx;min-width: 80rpx;}
	.teacher-avatar {width: 60rpx;height: 60rpx;border-radius: 60rpx;}
	.count {font-size: 24rpx;color: #999;padding-top: 10rpx;}
	.price-info{display: flex;flex-direction: column;align-items: center;}
	/* 支付方式 */
	.payment-section {background: #fff;border-radius: 12rpx;padding: 0 30rpx;}
	.section-title {display: block;font-size: 30rpx;color: #333;padding: 30rpx 0;border-bottom: 1rpx solid #eee;}
	.payment-item {display: flex;align-items: center;padding: 30rpx 0;border-bottom: 1rpx solid #eee;flex-direction: column;}
	.pay-type{width: 100%;padding: 20rpx;border: 1rpx solid #efefef;border-radius: 10rpx;display: flex;align-items: center;flex-direction: row;}
	.pay-type:last-child{margin-top: 20rpx;}
	.checked{border: 2rpx solid #EB6E30;}
	.checked .payment-name{color: #EB6E30;}
	.payment-icon {width: 60rpx;height: 60rpx;margin-right: 20rpx;}
	.payment-name {flex: 1;font-size: 30rpx;color: #333;}
	.check-icon {width: 40rpx;height: 40rpx;}
	.footer {position: fixed;bottom: 0;left: 0;right: 0;background: #fff;padding: 20rpx 30rpx;display: flex;justify-content: space-between;align-items: center;box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.06);flex-direction: row;}
	.price-box {flex: 1;}
	.price-label {font-size: 28rpx;color: #666;}
	.total-price {font-size: 36rpx;color: #EB6E30;font-weight: bold;}
	.pay-btn {background: #EB6E30;color: #fff;width: 240rpx;height: 80rpx;line-height: 80rpx;border-radius: 40rpx;font-size: 28rpx;margin: 0;}
</style>